package com.joinway.framework.core.groovy

import java.lang.reflect.Field

class GroovyDomain implements GroovyInterceptable, Serializable {

	String text
	
	Integer count
	
	Field[] fields
	
	public GroovyDomain(){
		fields = this.getClass().getDeclaredFields()
//		fields = GroovyDomain.class.getDeclaredFields()
//		println fields
	}
	
//	def invokeMethod(String name, Object args){
//		metaClass.getMetaMethod(name, args).invoke(this, args) 
//	}
	
	def invokeMethod(String name, Object args){
		def self = this
		def method = {
			metaClass.getMetaMethod(name, args)?.invoke(self, args)
		}
		
		if(fields && name.substring(0, 3).equals("get")){
			String prop = name.substring(3)
			prop = prop.substring(0, 1).toLowerCase() + prop.substring(1)
			
			Field target = fields.find(){it.getName().equals(prop)}
			if(!target){
				return method.call()
			}

			def value = this."$prop"
			
			if(value){
				return value
			}
			
			Class type = target.getType()
			switch(type){
				case String:
					value = ""
					break
				case [Integer, Double]:
					value = 0
					break
			}
			
			return value
//			if(type == String.class){
//				return ""
//			}else if(type == Integer.class || type == Short.class || type == Long.class || type == Double.class || type == Float.class){
//				return 0
//			}else if(type == Boolean.class){
//				return false
//			}else{
//				return value
//			}
		}else{
			return method.call()
		}
	}
	
	public static void getMyClassName(){
		println "test get my class name"
	}
}
